from typing import Optional
from fastapi import APIRouter, Request, Form, Cookie, Depends
from fastapi.responses import HTMLResponse, RedirectResponse
from utils import validate_session, get_user_settings, update_user_settings
from templates import templates

router = APIRouter()

@router.get("/settings", response_class=HTMLResponse)
async def settings_page(
    request: Request,
    session_id: Optional[str] = Cookie(None),
    username: Optional[str] = Cookie(None)
):
    if not session_id or not username or not validate_session(session_id, username):
        return RedirectResponse(url="/")
    
    user_settings = get_user_settings(username)
    return templates.TemplateResponse("settings.html", {
        "request": request,
        "username": username,
        "settings": user_settings
    })

@router.post("/update-settings")
async def update_settings(
    request: Request,
    theme: str = Form(...),
    notifications: str = Form(...),
    language: str = Form(...),
    font_size: str = Form(...),
    session_id: Optional[str] = Cookie(None),
    username: Optional[str] = Cookie(None)
):
    if not session_id or not username or not validate_session(session_id, username):
        return RedirectResponse(url="/")
        
    new_settings = {
        "theme": theme,
        "notifications": notifications == "on",
        "language": language,
        "font_size": font_size
    }
    update_user_settings(username, new_settings)
    
    return RedirectResponse(url="/settings?success=设置已更新", status_code=303)